import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_yres/model/shop/pdd_list.model.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:url_launcher/url_launcher.dart';

class PddShopDetailPage extends StatefulWidget {
  PddListModelData pddmodel;
  PddShopDetailPage({Key key, this.pddmodel}) : super(key: key);

  @override
  _PddShopDetailPageState createState() => _PddShopDetailPageState(pddmodel);
}

class _PddShopDetailPageState extends State<PddShopDetailPage> {
  PddListModelData pddmodel;
  _PddShopDetailPageState(this.pddmodel);

  String goods_name = ''; //商品名称
  var min_group_price = 0; //	最小拼团价（单位为分）
  var min_normal_price = 0; //	最小单买价格（单位为分）
  var coupon_discount = 0; //	优惠券面额，单位为分
  String mall_name = ''; //	店铺名字
  String commission; //	佣金（单位分）
  var commission_vip = 0; //	最高佣金（单位分）
  String content = ''; //详情
String url;
  List bannerData = []; //轮播图数组
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: PreferredSize(child: AppBar(), preferredSize: Size.fromHeight(0)),
      appBar: new AppBar(
        title: Text('商品详情',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: goods_name == ''
          ? Container()
          : Stack(children: <Widget>[
              Container(
                  height: ScreenUtil.getInstance().setHeight(1334) + kWindowstateHeight + 56,
                  child: SingleChildScrollView(
                      child: Column(children: <Widget>[
                    _buildBanner(),
                    Container(
                        margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(15)),
                        child: Text(
                          goods_name,
                          style: TextStyle(fontSize: 17),
                        )),
                    Container(
                      margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(15)),
                      child: Row(
                        children: <Widget>[
                          Container(
                            decoration: new BoxDecoration(
                              color: Colors.red,
                              //设置四周圆角 角度
                              borderRadius:
                                  BorderRadius.all(Radius.circular(4.0)),
                              //设置四周边框
                              border:
                                  new Border.all(width: 1, color: Colors.red),
                            ),
                            alignment: Alignment.center,
                            width: 60,
                            height: 20,
                            child: Text(
                              '券后价',
                              style: TextStyle(color: Colors.white),
                            ),
                            // color: Colors.red,
                          ),
                          Expanded(
                              child: Container(
                                margin: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(5), 0, 0,0 ),
                                  child: RichText(
                            textAlign: TextAlign.left,
                            text: TextSpan(
                                style: TextStyle(color: Colors.red),
                                children: [
                                  TextSpan(
                                      text: '¥',
                                      style: TextStyle(fontSize: 12.0)),
                                  TextSpan(
                                      text: min_group_price == null
                                          ? '0'
                                          : (min_group_price / 100 -
                                                  coupon_discount / 100)
                                              .toStringAsFixed(2),
                                      style: TextStyle(fontSize: 18.0)),
                                  TextSpan(
                                    text: min_normal_price == null
                                        ? '0'
                                        : (min_normal_price / 100)
                                            .toStringAsFixed(2),
                                    style: TextStyle(
                                        fontSize: 12.0,
                                        color: Colors.grey,
                                        decoration: TextDecoration.lineThrough,
                                        decorationColor: Colors.grey),
                                  ),
                                ]),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ))),
                          Expanded(
                              flex: 1,
                              child: Container(
                                margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
                                height: ScreenUtil.getInstance().setWidth(34),
                                color: Color.fromRGBO(250, 226, 226, 1),
                                child: Center(
                                    child: Text(
                                        commission.toString() == null
                                            ? '预估赚¥' + '0'
                                            :'预估赚¥' +  double.parse(commission).toStringAsFixed(2),
                                        style: TextStyle(
                                            color: Colors.red, fontSize: 10))),
                              ))
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(
                                    ScreenUtil.getInstance().setWidth(20), 0, ScreenUtil.getInstance().setWidth(20), 0),
                      alignment: Alignment.centerLeft,
                      child: Text(mall_name),
                    ),
                    Container(
                      margin: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                      child: Text('商品详情'),
                    ),
                    Container(
                      color: Colors.white,
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
                      child: Html(data: content),
                    )
                  ]))),
              // Positioned(
              //   top: kMargin10 * 3,
              //   left: kMargin10 * 3,
              //   child: IconButton(
              //       icon: ImageIcon(AssetImage("images/icon_detail_back.png")),
              //       onPressed: () {
              //         Navigator.pop(context);
              //       }),
              // ),
            ]),
      bottomNavigationBar: BottomAppBar(
          child: Row(
        children: <Widget>[
          Expanded(
              flex: 2,
              child: RaisedButton.icon(
                label: Text('分享'),
                icon: Icon(Icons.share),
                color: Colors.yellow,
                onPressed: () {},
              )),
          Expanded(
              flex: 3,
              child: RaisedButton.icon(
                label: Text('领券'),
                icon: Icon(Icons.receipt),
                color: Colors.red,
                onPressed: () {
                  _launchURL();
                },
              ))
        ],
      )),
    );
  }

  _launchURL() async {
    // String url = "taobao://item.taobao.com/item.html?id=41700658839";
    // String url = "pinduoduo://";
    String s = url.replaceAll('https:', 'pinduoduo://');
    if (await canLaunch(s)) {
      await launch(s);
    } else {
      throw 'Could not launch $url';
    }
  }

//轮播图组件
  _buildBanner() {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750),
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: bannerData.length,
        loop: false,
        autoplay: true,
        autoplayDelay: 15000,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        onTap: (index) {
          //点击轮播图事件
        },
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (Image.network(
      bannerData[index],
      fit: BoxFit.fill,
    ));
  }

  @override
  void initState() {
    _getLoginMsg();
    super.initState();
  }

  void _getLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    var token = preferences.get("token");
    print(token);
    print(this.pddmodel.goods_id);
    if (token == null || token == '') {
      //未登陆
      Navigator.of(context).pushNamed("login");
    } else {
      _getDetailUrl(this.pddmodel.goods_id.toString(), token);
    }
  }

//商品详情
  _getDetailUrl(String goods_id, String token) async {
    FormData data =
        new FormData.fromMap({'goods_id': goods_id, 'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetPddGoodsDetailUrl, data: data);
        print(Api.GetPddGoodsDetailUrl);
        print({'goods_id': goods_id, 'token': token});
    // await HttpUtil().post('http://taobao.mjuapp.com/app.php?c=Pdd&a=getGoodsDetail', data: data);
    Map userMap = json.decode(response.data);
    print('拼多多链接');
    // print(userMap['data']['goods_details']);
    print(userMap['data']);
    print(userMap['code']);
    if (userMap['code'] == 0) {
      if (mounted) {
        Map goods_details = userMap['data']['goods_details'];
        List  url_list = userMap['data']['url_list'];
        setState(() {
          url = url_list[0]["url"];
          bannerData = goods_details['goods_gallery_urls'];
          goods_name = goods_details['goods_name'];
           print(goods_name);
          mall_name = goods_details['mall_name'];
          min_group_price = goods_details['min_group_price'];
          min_normal_price = goods_details['min_normal_price'];
          commission = (double.parse(goods_details['commission'])/100).toString() ;
          commission_vip = goods_details['commission_vip'];
          coupon_discount = goods_details['coupon_discount'];
          content = goods_details['content'];
          if (bannerData.length > 0) {
            String imgHtml = "";
            for (String img in bannerData) {
              imgHtml = "<img src=\'" + img + "\'>" + imgHtml;
            }
            content =
                "<html><head><meta content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" name=\"viewport\"><style type=\"text/css\">img{display: inline-block;max-width: 100%}</style></head><body><p>" +
                    imgHtml +
                    "</p></body></html>";
          }
        });
      }
    }
  }
}
